﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Net.Mail;
using System.Text;
using System.Web;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;
using Microsoft.Reporting.WebForms;
using WebCommon;

public partial class Admin_ReportJournalVoucher : System.Web.UI.Page
{
    private DataTable dsPaymentDetail;
    protected void Page_Load(object sender, EventArgs e)
    {
        ReportViewer1.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
        if (!IsPostBack)
        {
            if (Request.QueryString["JournalVoucherId"] == null)
            {
                //Bind batch printing
                var payments = (DataTable)Session["Journal"];
                dsPaymentDetail = (DataTable)Session["JournalDetail"];
                ReportViewer1.LocalReport.DataSources["DSJournalVoucher_Journal"].Value = payments;
                ReportViewer1.LocalReport.Refresh();

                tblAttachFile.Visible = false;

            }
            else
            {
                //Bind single report
                string journalVoucherId = Request.QueryString["JournalVoucherId"];
                DbCommand cmd = new SqlCommand();
                cmd.CommandText = "_JournalVoucher_Print";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("JournalVoucherId", journalVoucherId));
                var journalResult = DataRepository.Provider.ExecuteDataSet(cmd);
                ReportViewer1.LocalReport.DataSources["DSJournalVoucher_Journal"].Value = journalResult.Tables[0];
                dsPaymentDetail = journalResult.Tables[1];
                ReportViewer1.LocalReport.Refresh();

                var journalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
                tblAttachFile.Visible = true;
                hpl_AttachedFile.NavigateUrl = "Download.ashx?path=" + Server.MapPath("~") +
                                               "\\AttachFile\\Journal\\&file=" + journalVoucher.AttachFile;
                hpl_AttachedFile.Target = "_blank";
                hpl_AttachedFile.Text = journalVoucher.AttachFile;
                UpdateJournalStatus(journalVoucher);
            }
        }
    }

    private void UpdateJournalStatus(JournalVoucher journalVoucher)
    {
        if (journalVoucher.IsApproved)
        {
            div_ApprovalStatus.InnerHtml = string.Format("<div class='notification {0} png_bg'> <div> {1} </div></div>", "success", "Approved");
            btn_RequestForApproval.Visible = false;
            btn_Approve.Visible = false;
            btn_RejectPopup.Visible = false;
        }
        else
        {
            if (journalVoucher.NotifyCode == "Rejected")
            {
                btn_RequestForApproval.Visible = true;
                div_ApprovalStatus.InnerHtml = string.Format("<div class='notification {0} png_bg'> <div> {1} </div></div>", "error", "Rejected - Reason: " + journalVoucher.Reason);
            }
            else
            {
                if (journalVoucher.IsSentForApproval == false)
                {
                    btn_RequestForApproval.Visible = true;
                    div_ApprovalStatus.InnerHtml = string.Format("<div class='notification {0} png_bg'> <div> {1} </div></div>", "attention", "Not send for approval yet");
                }
                else
                {
                    string authUserName = Context.User.Identity.Name.Split('\\')[1];
                    var user = DataRepository.InvoiceCheckingUserProvider.GetByUserId(authUserName);
                    if (user.Roles.Contains("Approval"))
                    {
                        btn_Approve.Visible = true;
                        btn_RejectPopup.Visible = true;
                        div_ApprovalStatus.InnerHtml = string.Format("<div class='notification {0} png_bg'> <div> {1} </div></div>", "attention", "Not approval yet");
                    }
                    else
                    {
                        btn_RequestForApproval.Visible = true;
                        btn_RequestForApproval.Text = "Resend Approval Request";
                        div_ApprovalStatus.InnerHtml = string.Format("<div class='notification {0} png_bg'> <div> {1} </div></div>", "information", "Wait for approval");
                    }
                }
            }
        }
    }

    void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
    {
        e.DataSources.Add(new ReportDataSource("DSJournalVoucher_JournalDetail", dsPaymentDetail));
    }
    protected void btn_RequestForApproval_Click(object sender, EventArgs e)
    {
        var journalVoucherId = Request.QueryString["JournalVoucherId"];
        var journalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
        var approvalUser = DataRepository.InvoiceCheckingUserProvider.GetByUserId(journalVoucher.ApprovalBy);
        var content = new StringBuilder();
        content.Append("Dear Mr / Ms " + approvalUser.Fullname + "<br/><br/>");
        content.Append(string.Format("Please click the link {0} to see details. <br/><br/>", HttpContext.Current.Request.Url.AbsoluteUri));
        content.Append(string.Format("As this is an autogenerated E-mail please do not reply. <br/>"));
        content.Append(string.Format("Log on to VIPs system to find out more! <br/> <br/>"));
        content.Append(
            "Important Notice: This communication (including any attachments) is intended for the use of the intended recipient(s) only and may contain information that is confidential, privileged or legally protected. Any unauthorized use or dissemination of this communication is strictly prohibited. If you have received this communication in error, please immediately notify the sender by return e-mail message and delete all copies of the original communication. Thank you for your cooperation. ");
        var config = new SharedFunction.SmtpMailConfig
            {
                EnableSSL = false,
                MailAddress = "hcm.sql@internationalsos.com",
                Password = "P@ssword01",
                SMTPPort = 25,
                SMTPServer = "10.2.2.1"
            };
        string subject = "Request Approval For Journal Voucher " + journalVoucherId;
        var attachments = new Attachment[] { };
        var toAddress = new MailAddressCollection { approvalUser.Email };
        SharedFunction.SendEmail(config, content.ToString(), subject, attachments, toAddress, null, null, MailPriority.Normal);
        journalVoucher.IsSentForApproval = true;
        journalVoucher.NotifyCode = "";
        DataRepository.JournalVoucherProvider.Update(journalVoucher);
        UpdateJournalStatus(journalVoucher);
    }

    protected void btn_Reject_Click(object sender, EventArgs e)
    {
        var journalVoucherId = Request.QueryString["JournalVoucherId"];
        var journalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
        journalVoucher.IsSentForApproval = false;
        journalVoucher.NotifyCode = "Rejected";
        journalVoucher.Reason = dataVoidReason.Text.Substring(1);
        DataRepository.JournalVoucherProvider.Update(journalVoucher);
        UpdateJournalStatus(journalVoucher);
    }
    protected void btn_Approve_Click(object sender, EventArgs e)
    {
        var journalVoucherId = Request.QueryString["JournalVoucherId"];
        var journalVoucher = DataRepository.JournalVoucherProvider.GetByJournalVoucherId(journalVoucherId);
        journalVoucher.ApprovedDate = DateTime.Now;
        string authUserName = Context.User.Identity.Name.Split('\\')[1];
        journalVoucher.ApprovalBy = authUserName;
        journalVoucher.IsApproved = true;
        journalVoucher.NotifyCode = "";
        journalVoucher.IsCompleted = true;
        DataRepository.JournalVoucherProvider.Update(journalVoucher);
        UpdateJournalStatus(journalVoucher);
    }
}
